package cst.a330gjq.startproject_330gjq.model;

import cst.a330gjq.startproject_330gjq.bean.WeatherResult;
import cst.a330gjq.startproject_330gjq.iface.WeatherIface;
import cst.a330gjq.startproject_330gjq.listener.WeatherListener;
import cst.a330gjq.startproject_330gjq.service.Weather51Service;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 新生活 on 2017/5/11.
 */

public class Weather51Model implements WeatherIface {
    private Retrofit retrofit;
    private Weather51Service service;
    public static final String BASE_URL = "http://weather.51wnl.com/weatherinfo/";

    public Weather51Model() {
        //super(BASE_URL);
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Override
    public void getWeather(String cityNo, final WeatherListener l) {
        service = retrofit.create(Weather51Service.class);
        Call<WeatherResult> call = service.getWeather(cityNo, 1);
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call,
                                   Response<WeatherResult> response) {
                if (response.isSuccessful() && response.body() != null) {
                    l.onResponse(response.body().getWeatherInfo());
                } else {
                    l.onFail("解析错误！");
                }
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                l.onFail(t.toString());
            }
        });
    }
}